using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DocumentCreationSystem.Views;

namespace DocumentCreationSystem
{
    /// <summary>
    /// 右键重命名功能测试
    /// </summary>
    public class TestRenameFunction
    {
        public static async Task Main(string[] args)
        {
            Console.WriteLine("=== 右键重命名功能测试 ===\n");

            try
            {
                // 测试文件名验证
                TestFileNameValidation();

                // 测试重命名对话框逻辑
                await TestRenameDialogLogic();

                // 测试文件重命名操作
                await TestFileRenameOperation();

                Console.WriteLine("\n=== 测试完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"测试失败: {ex.Message}");
                Console.WriteLine($"详细错误: {ex}");
            }
        }

        private static void TestFileNameValidation()
        {
            Console.WriteLine("1. 测试文件名验证");

            var testCases = new[]
            {
                new { Name = "正常文件名.txt", Expected = true, Description = "正常文件名" },
                new { Name = "文件名包含空格.txt", Expected = true, Description = "包含空格的文件名" },
                new { Name = "file<name>.txt", Expected = false, Description = "包含无效字符<>" },
                new { Name = "file|name.txt", Expected = false, Description = "包含无效字符|" },
                new { Name = "file:name.txt", Expected = false, Description = "包含无效字符:" },
                new { Name = "file*name.txt", Expected = false, Description = "包含无效字符*" },
                new { Name = "file?name.txt", Expected = false, Description = "包含无效字符?" },
                new { Name = "file\"name.txt", Expected = false, Description = "包含无效字符\"" },
                new { Name = "file/name.txt", Expected = false, Description = "包含无效字符/" },
                new { Name = "file\\name.txt", Expected = false, Description = "包含无效字符\\" },
                new { Name = "CON.txt", Expected = false, Description = "系统保留名称CON" },
                new { Name = "PRN.txt", Expected = false, Description = "系统保留名称PRN" },
                new { Name = "COM1.txt", Expected = false, Description = "系统保留名称COM1" },
                new { Name = "LPT1.txt", Expected = false, Description = "系统保留名称LPT1" },
                new { Name = "", Expected = false, Description = "空名称" },
                new { Name = "   ", Expected = false, Description = "只有空格" },
                new { Name = "文件名.", Expected = false, Description = "以点结尾" },
                new { Name = "文件名 ", Expected = false, Description = "以空格结尾" },
                new { Name = new string('a', 256), Expected = false, Description = "超长文件名" },
                new { Name = "中文文件名.txt", Expected = true, Description = "中文文件名" },
                new { Name = "123456.txt", Expected = true, Description = "数字文件名" },
                new { Name = "file-name_test.txt", Expected = true, Description = "包含连字符和下划线" }
            };

            int passCount = 0;
            foreach (var testCase in testCases)
            {
                var result = IsValidFileName(testCase.Name);
                var status = result == testCase.Expected ? "✅" : "❌";
                Console.WriteLine($"  {status} {testCase.Description}: '{testCase.Name}' -> {result}");
                
                if (result == testCase.Expected)
                    passCount++;
            }

            Console.WriteLine($"验证测试完成: {passCount}/{testCases.Length} 项通过\n");
        }

        private static async Task TestRenameDialogLogic()
        {
            Console.WriteLine("2. 测试重命名对话框逻辑");

            // 模拟重命名对话框的验证逻辑
            var testCases = new[]
            {
                new { Original = "test.txt", New = "newtest.txt", ShouldEnable = true },
                new { Original = "test.txt", New = "test.txt", ShouldEnable = false }, // 相同名称
                new { Original = "test.txt", New = "", ShouldEnable = false }, // 空名称
                new { Original = "test.txt", New = "new<test>.txt", ShouldEnable = false }, // 无效字符
                new { Original = "folder", New = "newfolder", ShouldEnable = true },
                new { Original = "folder", New = "CON", ShouldEnable = false } // 保留名称
            };

            foreach (var testCase in testCases)
            {
                var isValid = IsValidFileName(testCase.New);
                var shouldEnable = isValid && !string.IsNullOrWhiteSpace(testCase.New) && testCase.New != testCase.Original;
                var status = shouldEnable == testCase.ShouldEnable ? "✅" : "❌";
                
                Console.WriteLine($"  {status} '{testCase.Original}' -> '{testCase.New}': 按钮应该{(testCase.ShouldEnable ? "启用" : "禁用")}");
            }

            Console.WriteLine("对话框逻辑测试完成\n");
        }

        private static async Task TestFileRenameOperation()
        {
            Console.WriteLine("3. 测试文件重命名操作");

            var testDir = Path.Combine(Environment.CurrentDirectory, "RenameTest");
            
            try
            {
                // 清理并创建测试目录
                if (Directory.Exists(testDir))
                {
                    Directory.Delete(testDir, true);
                }
                Directory.CreateDirectory(testDir);

                // 创建测试文件
                var testFile = Path.Combine(testDir, "原始文件.txt");
                await File.WriteAllTextAsync(testFile, "这是测试文件内容");

                // 创建测试文件夹
                var testFolder = Path.Combine(testDir, "原始文件夹");
                Directory.CreateDirectory(testFolder);

                Console.WriteLine("  创建测试文件和文件夹");

                // 测试文件重命名
                var newFileName = Path.Combine(testDir, "重命名文件.txt");
                if (File.Exists(testFile))
                {
                    File.Move(testFile, newFileName);
                    Console.WriteLine("  ✅ 文件重命名成功: 原始文件.txt -> 重命名文件.txt");
                }

                // 测试文件夹重命名
                var newFolderName = Path.Combine(testDir, "重命名文件夹");
                if (Directory.Exists(testFolder))
                {
                    Directory.Move(testFolder, newFolderName);
                    Console.WriteLine("  ✅ 文件夹重命名成功: 原始文件夹 -> 重命名文件夹");
                }

                // 验证重命名结果
                if (File.Exists(newFileName))
                {
                    var content = await File.ReadAllTextAsync(newFileName);
                    if (content == "这是测试文件内容")
                    {
                        Console.WriteLine("  ✅ 文件内容保持不变");
                    }
                    else
                    {
                        Console.WriteLine("  ❌ 文件内容发生变化");
                    }
                }

                if (Directory.Exists(newFolderName))
                {
                    Console.WriteLine("  ✅ 文件夹重命名后存在");
                }

                // 测试重复名称检查
                var duplicateFile = Path.Combine(testDir, "重命名文件.txt");
                if (File.Exists(duplicateFile))
                {
                    Console.WriteLine("  ✅ 重复名称检查: 目标文件已存在");
                }

                Console.WriteLine("文件重命名操作测试完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"  ❌ 文件重命名操作测试失败: {ex.Message}");
            }
            finally
            {
                // 清理测试目录
                try
                {
                    if (Directory.Exists(testDir))
                    {
                        Directory.Delete(testDir, true);
                        Console.WriteLine("  🧹 测试目录已清理");
                    }
                }
                catch
                {
                    Console.WriteLine("  ⚠️ 测试目录清理失败");
                }
            }
        }

        /// <summary>
        /// 验证文件名是否有效（复制自主程序的逻辑）
        /// </summary>
        private static bool IsValidFileName(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                return false;

            // 检查是否包含无效字符
            var invalidChars = Path.GetInvalidFileNameChars();
            if (fileName.Any(c => invalidChars.Contains(c)))
                return false;

            // 检查是否为保留名称
            var reservedNames = new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" };
            var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName).ToUpper();
            if (reservedNames.Contains(nameWithoutExtension))
                return false;

            // 检查长度
            if (fileName.Length > 255)
                return false;

            // 检查是否以点或空格结尾
            if (fileName.EndsWith(".") || fileName.EndsWith(" "))
                return false;

            return true;
        }
    }
}
